package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.Set;

import com.ruoyi.common.constant.ConfigConstant;
import com.ruoyi.common.utils.AesUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.impl.SmsSendRecordServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SmsSendRecordServiceImpl smsSendRecordService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(HttpServletRequest request, @RequestBody LoginBody loginBody) throws Exception {
        String tenant= request.getHeader("tenant");
        AjaxResult ajax = AjaxResult.success();
        /**登录是否需要认证短信验证码**/
        String isNeedSmsCode = configService.getItemValueByItemKey(ConfigConstant.IS_NEED_SMS_Code, "0");
        String password=loginBody.getPassword();
        String username=loginBody.getUsername();
        if("1".equals(isNeedSmsCode)){

            SysUser user = userMapper.getUseyByphonenumber(loginBody.getPhonenumber());
            if (user==null) {
                return AjaxResult.error("手机号对应用户不存在或登录受限");
            }
            //短信验证码登录，免密码登录生成token
            Map<String, Object> resMap = smsSendRecordService.verifyValidateCode(loginBody.getPhonenumber(),loginBody.getSmsValidatecode());
            if(resMap.get("errorNo").toString().equals("-1")){
                //验证失败
                return AjaxResult.error(resMap.get("errorInfo").toString());
            }
            else{
                //验证成功,将免密码登录
                password= AesUtils.decrypt( user.getPassword2());
                username=user.getUserName();
            }
        }
        // 生成令牌
        String token = loginService.login(tenant, username, password, loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
